# 构建GDP动态柱状图
from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
from pyecharts.options import *

# 数据处理
f = open("D:/Code/KnowCode/my_python/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv", 'r', encoding="GB2312")
data_lines = f.readlines()
f.close()

# 删除标头
data_lines.pop(0)

data_dict = {}
for line in data_lines:
    data_list = line.split(",")
    year = int(data_list[0])
    country = data_list[1]
    gdp = float(data_list[2])
    try:
        data_dict[year].append([country, gdp])
    except KeyError:
        data_dict[year] = []
        data_dict[year].append([country, gdp])

# print(data_dict)

# 构建柱状图
# 字典关键字可能不按年份大小顺序，导致构建bar的顺序出错
# 先对字典关键字进行排序
year_list = sorted(data_dict.keys())

timeLine = Timeline({"theme": ThemeType.LIGHT})

for year in year_list:
    # 排序
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    # 取前8名
    year_data = data_dict[year][0:8]
    x_data = []
    y_data = []
    for country_gdp in year_data:
        x_data.append(country_gdp[0])
        y_data.append(country_gdp[1] / 1000000000)

    bar = Bar()
    bar.add_xaxis(x_data[::-1])
    bar.add_yaxis("GDP(亿)", y_data[::-1], label_opts=LabelOpts(position="right"))
    bar.reversal_axis()
    bar.set_global_opts(
        title_opts=TitleOpts(title=f"{year}年全球前8国家GDP数据")
    )

    timeLine.add(bar, str(year))

timeLine.add_schema(
    play_interval=500,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=False
)

timeLine.render("1960-2019年全球GDP前8国家.html")
